import os
import socket
import threading


def getReqSocket(newSockt, ipPort):
    print(ipPort)
    recvData = newSockt.recv(4096)
    if len(recvData) == 0:
        print("关闭浏览器！", ipPort)
        newSockt.close()
        return
    recvClientContent = recvData.decode("utf-8")
    reqList = recvClientContent.split(" ", 2)
    reqUrl = reqList[1]
    if reqUrl == "/":
        reqUrl = "/index.html"
    print("客服端接收的数据：", reqUrl)
    # with open("static/index.html", "rb") as file:
    try:
        with open("static" + reqUrl, "rb") as file:
            fileData = file.read()
    except Exception as e:
        responseLine = "HTTP/1.1 404 Not Found\r\n"
        responseHeader = "Server: PWS1.0\r\n"
        with open("static/error.html", "rb") as file:
            fileData = file.read()
        responseBody = fileData
        responseData = (responseLine + responseHeader + "\r\n").encode(
            "utf-8"
        ) + responseBody
        newSockt.send(responseData)
    else:
        responseLine = "HTTP/1.1 200 OK\r\n"
        responseHeader = "Server: PWS1.0\r\n"
        responseBody = fileData
        responseData = (responseLine + responseHeader + "\r\n").encode(
            "utf-8"
        ) + responseBody
        newSockt.send(responseData)
    finally:
        print("关闭套接字", ipPort)
        newSockt.close()


def main():
    path = os.getcwd()
    print(path)
    tcpServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcpServerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcpServerSocket.bind(("", 8888))
    tcpServerSocket.listen(128)
    while True:
        newSockt, ipPort = tcpServerSocket.accept()
        subThreading = threading.Thread(target=getReqSocket, args=(newSockt, ipPort))
        subThreading.setDaemon(True)
        subThreading.start()


if __name__ == "__main__":
    main()
